﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

using InTheHand.Net.Sockets;

using TTServer.Messages;
using libReadWrite;
using libCommonClass;

namespace TTServer
{
    class BluetoothServerThread
    {
        private BluetoothClient m_bluetoothClient = null;
        private Thread th = null;
        private BigEndianReader _bigEndianReader = null;
        private BigEndianWriter _bigEndianWriter = null;
        private MessageReader msgReader = null;

        public BluetoothServerThread(BluetoothClient btClient)
        {
            if (btClient != null) //Kiểm tra giá trị của đối số truyền vào
            {
                this.m_bluetoothClient = btClient;

                var s = btClient.GetStream();
                this._bigEndianReader = new BigEndianReaderForBluetooth(new System.IO.BinaryReader(s));
                this._bigEndianWriter = new BigEndianWriterForBluetooth(new System.IO.BinaryWriter(s));

                msgReader = new MessageReader(this._bigEndianReader);
            }
            else
            {
                throw new Exception("Đối số truyền vào không phù hợp");
            }
        }

        public void CreateAndStartThread()
        {
            th = new Thread(new ThreadStart(Run));
            th.Priority = ThreadPriority.Normal;
            th.Start();
        }

        public void TerminateAll()
        {
            try
            {
                if (m_bluetoothClient != null)
                {
                    m_bluetoothClient.Close();
                }
            }
            catch { 
            
            }
        }

        public void Run()
        {
            while (true)
            {
                try
                {

                    TTMessage msg = msgReader.GetMessage();

                    //if (msg != null)
                    //{
                    //    GlobalDispatcher.addToQueue(new CTask());
                    //}
                }
                catch (Exception ex)
                {
                    //Cần bổ sung thread đã thoát hoàn toàn trong đây chưa
                    TerminateAll();
                    break;
                }
            }
        }
    }
}
